﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using System.Windows.Forms;
using Contract;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace client
{
    public partial class Login : Form
    {
        public static string PCN;
        public static IDataUploader Proxy;
        public static IService_Allocation Proxy1;
        public NetTcpBinding binding;
        EndpointAddress address,address1;
        ChannelFactory<IService_Allocation> channel1;
        ChannelFactory<IDataUploader> channel;
        public Login()
        {
            //Create channel
            InitializeComponent();
            binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.SendTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            
            address1 = new EndpointAddress("net.tcp://localhost:8888/Service_Allocation");
            channel1 = new ChannelFactory<IService_Allocation>(binding, address1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            address = new EndpointAddress("net.tcp://"+Proxy1.agentAllocation().ToString() +":8000/DataUploader");
            channel = new ChannelFactory<IDataUploader>(binding, address);
            Proxy = channel.CreateChannel();
            PCN = textBox1.Text.Trim();
            string Password = textBox2.Text.Trim();


            if (PCN == "" || Password == "")
            {
                MessageBox.Show("Can't be empty");
            }
            else
            {
                if (Proxy.Login(PCN, Password))
                {
                    Form1 f1 = new Form1(PCN);
                    f1.Show();
                }
                else
                    MessageBox.Show("fail-remote");
            }

            //Register client in server
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    Proxy.sendClientIP(ip);
                }
            }
            channel.Close();
            this.Hide();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Register fr = new Register();
            fr.Show();
        }
    }
}
